import { WeaLocaleProvider, WeaFormItem, WeaSearchGroup, WeaTools, WeaInputLocale } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { isFunction, toLower, isObject } from 'lodash';
import { message } from 'antd';
import { toJS } from 'mobx';

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

const createCondition = (domkey, labelId, defaultLabel, otherParams = { label: '' }) => {
  let obj = {
    fieldcol: 14,
    labelcol: 8,
    value: "",
    colSpan: 2,
    viewAttr: 2,
    conditionType: 'SWITCH',
    formItemType: 'SWITCH',
    ...otherParams,

    domkey: Array.isArray(domkey) ? domkey : [domkey],
    label: labelId !== '' ? getLabel(labelId, defaultLabel) : otherParams.label,
  };
  if (otherParams.viewAttr == '3' && !otherParams.rules) {
    obj.rules = 'required';
  }
  return obj;
};

const hasKey = (datas, key, delKeys = []) => {
  let bool = false, keys = toLower(key);
  datas.forEach(item => {
    item.items.find(o => toLower(getKey(o)) === keys && delKeys.indexOf(keys) <= -1) && (bool = true);
  })
  return bool;
};
export default {

  createConditions: (array) => {
    return array.map((arr) => createCondition(arr[0], arr[1], arr[2], arr.length > 3 ? arr[3] : undefined));
  },

  getSearchs: (form, conditions, otherParams = { className: '', cusComIndex: 0, cusCom: null, noTitle: false, col: 1 }, hide, onChange) => {
    const { isFormInit } = form;
    const formParams = form.getFormParams();
    let group = [];
    let col = otherParams.col || 1;
    isFormInit && conditions && conditions.map((c, index) => {
      let items = [];
      if (otherParams.cusCom && index === otherParams.cusComIndex) {
        items.push({ com: otherParams.cusCom, col: 1 });
      } else {
        c.items && c.items.map(fields => {
          if (!fields) {
            return;
          }
          let fieldsOnChange = fields.onChange;
          delete fields.onChange;
          items.push({
            com: (
              <div className={otherParams.className}>
                <WeaFormItem
                  label={isObject(fields.label) ? fields.label : `${fields.label}`}
                  labelCol={{ span: `${fields.labelcol}` }}
                  wrapperCol={{ span: `${fields.fieldcol}` }}
                  error={form.getError(fields)}
                  ratio1to2
                  tipPosition="bottom">
                  <WeaSwitch fieldConfig={fields} form={form} formParams={formParams} onChange={(...args) => {
                    isFunction(onChange) && onChange(...args);
                    isFunction(fieldsOnChange) && fieldsOnChange(...args);
                  }} />
                  {
                    fields.showOtherCom && c.otherCom &&
                    <span style={{ display: 'inline-block', marginTop: 2, marginLeft: 10 }}>
                      {fields.showOtherCom && c.otherCom}
                    </span>
                  }
                </WeaFormItem>
              </div>),
            col: col,
            hide: form.isHide(fields, (keys, allParams) => {
              let bool = false;
              isFunction(hide) && (bool = hide(keys, allParams));
              return bool;
            }),
          })
        });
      }
      let searchGroup = otherParams.noTitle ? (
        <WeaSearchGroup needTigger={true} showGroup={c.defaultshow} items={items} />) : (
          <WeaSearchGroup title={c.title} needTigger={true} showGroup={c.defaultshow} items={items} />);
      group.push(searchGroup)
    });
    return group;
  },

  icon: <span className='icon-coms-doc' />,
  iconClassName: 'icon-coms-doc',
  iconBgColor: '#F14A2D ',
  rightStr: 'DocSecCategoryAdd:Add',
  hrIcon: <span className="icon-coms-hrm" />,
  hrIconClassName: 'icon-coms-hrm',
  hrIconBgColor: '#008572',
  hrRightStr: 'HrmContractTypeAdd:Add',

  catchApiError: (result) => {
    return new Promise((resolve, reject) => {
      if (!result.api_status) {
        message.error(result.msg || getLabel(30651, '操作失败'));
        reject(result);
        return;
      }
      resolve(result);
    });
  },

  readOnly: (datas) => {
    let _datas = toJS(datas);
    _datas.forEach((item, index) => {
      item.items.forEach((o, l) => _datas[index].items[l].viewAttr = 1);
    })
    return _datas;
  },

  getUpdateDatas: (result, datas, delKeys = []) => {
    let updateField = {};
    Object.keys(result).forEach(v => {
      hasKey(datas, v, delKeys) && (updateField[v] = { value: result[v] });
    })
    return updateField;
  },

  // 不含IE11
  isIE: () => navigator.appName == 'Microsoft Internet Explorer',

  isIE11: () => (/Trident\/7\./).test(navigator.userAgent),
  decodeMultiLang: (str) => {
    if (!str || str.indexOf("base64_") != 0) {
      return str;
    }
    let base64Str = str.substr(7);
    let multiStr = WeaTools.Base64.decode(base64Str);
    let currentStr = WeaInputLocale.getCurrentLabel(multiStr, WeaLocaleProvider.getUserLanguage());
    return currentStr;
  }

}